package com.jar.springbootsecuritydemo.config;


import com.jar.springbootsecuritydemo.pojo.bo.Audience;
import com.jar.springbootsecuritydemo.pojo.bo.SecurityUser;
import com.jar.springbootsecuritydemo.utils.JwtTokenUtil;
import com.jar.springbootsecuritydemo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器 【验证token有效性】
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private Audience audience;

    @Resource
    private RedisUtil redisUtil;


    /**
     * 每次请求都会到jwt过滤器中验证jwt有效性
     *
     * @param request  request
     * @param response response
     * @param chain    chain
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        String token = jwtTokenUtil.getToken(request);
        if (token != null) {

            String username = jwtTokenUtil.getUsername(token, audience.getSecret());

            if (username == null) {
                chain.doFilter(request, response);
                return;
            }

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null) {

                String tokenKey = jwtTokenUtil.getTokenKey(username);

                // 从redis中查询token是否存在来判断有效期
                String redisToken = redisUtil.get(tokenKey);

                if (redisToken == null || !redisToken.equals(token)) {
                    chain.doFilter(request, response);
                    return;
                }

                // 通过用户名加载SpringSecurity用户
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                // 校验Token的有效性
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails
                        , null
                        , userDetails.getAuthorities());

                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                //以后可以security中取得SecurityUser信息
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }

        }
        chain.doFilter(request, response);
    }
}


